const {
  Socket
} = require("dgram");
const express = require("express");
const http = require("http");
const path = require("path");

// express
const app = express();
const server = http.createServer(app);
app.use(express.static(path.resolve(__dirname, "public")));
// 监听端口
server.listen(5008, () => {
  console.log("在网页中打开 http://localhost:5008");
});


// 用户交互代码
const socketIO = require("socket.io");
const io = socketIO(server);
// 当前人数，超过两个人变成观战模式


let lock = true;
let userId = [];
let staffAID, staffBID;

io.on('connection', (socket) => {

  socket.on('login', function () {
    userId.push({
      id: socket.id
    })
    // 给玩家分配颜色,并且开始游戏
    if (userId.length == 2 && lock) {
      staffAID = userId[0].id;
      staffBID = userId[1].id;
      io.to(staffAID).emit('start', 1);
      io.to(staffBID).emit('start', 2);
      lock = false;

      io.emit('gaming') // 告诉玩家开始游戏了
    }
    
  })
  
  socket.on('userDown',function(options){
    socket.broadcast.emit('userDown',options);
  })
  // 游戏结束
  socket.on('gameover',function(options){
    io.emit('gameover');
  })

  // 告诉观众游戏进行中
  if (lock == false) {
    io.to(socket.id).emit('gaming')
  }

  //断开连接
  socket.on("disconnect", () => {

    if (socket.id == staffAID || socket.id == staffBID) {

      //给其他人广播，游戏中断
      socket.broadcast.emit('stop');
      lock = true;
    }

    userId = userId.filter(item => item.id != socket.id);
  });
})